package com.bobbygu.bobbyapp.base;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;
import android.support.multidex.MultiDex;

import com.bobbygu.bobbyapp.R;
import com.bobbygu.bobbyapp.utils.crashcatch.CrashExceptionHandler;
import com.bobbygu.libnet.baserx.RxManager;
import com.bobbygu.libnet.common.ApiConstants;
import com.bobbygu.bobbyapp.BuildConfig;
import com.bobbygu.libspeech.SpeechUtility;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.FormatStrategy;
import com.orhanobut.logger.Logger;
import com.orhanobut.logger.PrettyFormatStrategy;
import com.qihoo360.replugin.RePluginApplication;
import com.wanjian.cockroach.Cockroach;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayDeque;
import java.util.Date;
import java.util.Deque;
import java.util.Locale;

import cn.jpush.android.api.JPushInterface;

/**
 * MyApplication
 * <p>
 * author: 顾博君 <br>
 * time:   2017/10/19 18:47 <br>
 * e-mail: gubojun@csii.com.cn <br>
 * </p>
 */
public class MyApplication extends RePluginApplication {
    private static final int MAX_ACTIVITIES_IN_LOG = 50;
    private static MyApplication instance;
    private boolean isTrackActivities = true;
    private static boolean isInBackground = true;
    public static Deque<String> activityLog = new ArrayDeque<>(MAX_ACTIVITIES_IN_LOG);
    private RxManager mRxManager = new RxManager();

    public boolean isTrackActivities() {
        return isTrackActivities;
    }

    /**
     * 获取Application实例
     *
     * @return Application实例
     */
    public static MyApplication getInstance() {
        return instance;
    }

    //构造方法
    public MyApplication() {
        instance = this;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //讯飞语音合成
        SpeechUtility.createUtility(this, "appid=" + getString(R.string.app_id));
        //JPush消息推送
        JPushInterface.setDebugMode(BuildConfig.DEBUG);
        JPushInterface.init(this);
        //服务器地址
        ApiConstants.setProductHost(BuildConfig.BASEURL);
        Fresco.initialize(this);
        //异常捕获
        Cockroach.install(new CrashExceptionHandler(this, mRxManager));
        registerActivityLifecycle();//注册activity生命周期
        initLog();//初始化日志
    }

    @Override
    public void onTerminate() {
        // 程序终止的时候执行
        Logger.d("onTerminate");
        mRxManager.clear();
        super.onTerminate();
    }

    /**
     * 分包
     *
     * @param base Context
     */
    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    /**
     * 注册activity生命周期
     */
    private void registerActivityLifecycle() {
        registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
            int currentlyStartedActivities = 0;
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);

            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                if (isTrackActivities) {
                    activityLog.add(dateFormat.format(new Date()) + ": " + activity.getClass().getSimpleName() + " created\n");
                }
            }

            @Override
            public void onActivityStarted(Activity activity) {
                currentlyStartedActivities++;
                isInBackground = (currentlyStartedActivities == 0);
                //Do nothing
            }

            @Override
            public void onActivityResumed(Activity activity) {
                if (isTrackActivities) {
                    activityLog.add(dateFormat.format(new Date()) + ": " + activity.getClass().getSimpleName() + " resumed\n");
                }
            }

            @Override
            public void onActivityPaused(Activity activity) {
                if (isTrackActivities) {
                    activityLog.add(dateFormat.format(new Date()) + ": " + activity.getClass().getSimpleName() + " paused\n");
                }
            }

            @Override
            public void onActivityStopped(Activity activity) {
                //Do nothing
                currentlyStartedActivities--;
                isInBackground = (currentlyStartedActivities == 0);
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
                //Do nothing
            }

            @Override
            public void onActivityDestroyed(Activity activity) {
                if (isTrackActivities) {
                    activityLog.add(dateFormat.format(new Date()) + ": " + activity.getClass().getSimpleName() + " destroyed\n");
                }
            }
        });
    }

    /**
     * 初始化日志
     */
    private void initLog() {
        FormatStrategy formatStrategy = PrettyFormatStrategy.newBuilder()
                .tag(Constant.COMMON_LOG_TAG)
                .build();

        Logger.addLogAdapter(new AndroidLogAdapter(formatStrategy) {
            @Override
            public boolean isLoggable(int priority, String tag) {
                return BuildConfig.DEBUG;
            }
        });
    }
}
